// 云函数入口文件
const cloud = require('wx-server-sdk')
// 初始化之前,声明云环境id
const env = 'cloud1-4g42994n5a7bf42f'

cloud.init()

// 声明数据库的环境
const db = cloud.database({
  env
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let openId=wxContext.OPENID
  // console.log('wxContext', wxContext);
  // console.log('event',event);

  let eventName = await db.collection('myTomatoes').where({
    username:'tomatoes'
  }).get()
  // console.log(eventName);
  let tomatoes=eventName.data[0]
  if (eventName.data.length == 0) { //集合为空
    return await db.collection('myTomatoes').add({//添加
      data: {
        user: openId,
        username: 'tomatoes',
        dayTomatoesArr: [{
          createTime: new Date().getTime(),
          createDate:new Date().toLocaleString(),
          dayTomatoes: event.dayTomatoes,
        }],
        totalTomatoes:event.totalTomatoes,
      }
    })
  } else {//集合不为空
    let dayTomatoesArr =eventName.data[0].dayTomatoesArr;
    dayTomatoesArr.push({
      createTime: new Date().getTime(),
      dayTomatoes: 1
    });
    console.log('dayTomatoesArr', dayTomatoesArr);
    let totalTomatoes = eventName.data[0].totalTomatoes;
    totalTomatoes += 1;
    await db.collection('myTomatoes').where({
      username:'tomatoes'
    }).update({//更新
      data: {
        user: openId,
        dayTomatoesArr: dayTomatoesArr,
        totalTomatoes: totalTomatoes,
        username:'tomatoes'
      }
    })
  }

  return {
    tomatoes
  }
}